package net.xdclass.base_project.producerConfig;

import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.common.serialization.StringSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.annotation.EnableKafka;
import org.springframework.kafka.core.DefaultKafkaProducerFactory;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.core.ProducerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * @author sqz
 * @Description: kafka生产者配置类
 * @date 2019/9/23 16:33
 */
@Configuration
@EnableKafka
public class KafkaProducerConfig {

    @Value("${spring.kafka.producer.bootstrap-servers}")
    private String servers;
    @Value("${spring.kafka.producer.retries}")
    private int retries;
    @Value("${spring.kafka.producer.batch-size}")
    private int batchSize;
    @Value("${spring.kafka.producer.linger.ms}")
    private int linger;
    @Value("${spring.kafka.producer.buffer-memory}")
    private int bufferMemory;
    private final Logger logger = LoggerFactory.getLogger(KafkaProducerConfig.class);

    public Map<String, Object> producerConfigs() {
        logger.error("linger:{},batchSize:{}",linger,batchSize);
        Map<String, Object> props = new HashMap<>();
        // Kafka 服务端的主机名和端口号
        props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, servers);
        // 消息发送最大尝试次数
        props.put(ProducerConfig.RETRIES_CONFIG, retries);
        //all是等待所有副本节点的应答,all效率最慢，但是最安全,
        props.put(ProducerConfig.ACKS_CONFIG, "all");
        // 一批消息处理大小
        props.put(ProducerConfig.BATCH_SIZE_CONFIG, batchSize);
        // 增加服务端请求延时，达到多少秒的时候发送
        props.put(ProducerConfig.LINGER_MS_CONFIG, linger);
        // 发送者总的缓存区内存大小
        props.put(ProducerConfig.BUFFER_MEMORY_CONFIG, bufferMemory);
        props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        //自定义分区，指定分区
        //props.put(ProducerConfig.PARTITIONER_CLASS_CONFIG, "net.xdclass.base_project.producerConfig.KafkaProducerPartitionConfig");
        return props;
    }


    public ProducerFactory<String, Object> producerFactory() {
        return new DefaultKafkaProducerFactory<>(producerConfigs());
    }

    @Bean
    public KafkaProducer<String, String> kafkaProducer(){
        return new KafkaProducer<String, String>(producerConfigs(), new StringSerializer(), new StringSerializer());
    }

    @Bean
    public KafkaTemplate<String, Object> kafkaTemplate() {
        return new KafkaTemplate<String, Object>(producerFactory());
    }
}

